import { keepDecimal, makeDiv } from "../../../core/utils/utils";
import { GoodTypeDefine } from "../../defines/good_type";
import { BaseHUDPart } from "../base_hud_part";

export class HUDBackpickPage extends BaseHUDPart{
  constructor(root){
    super(root);
  }

  createElements(parent){
    this.element = makeDiv(parent, 'backpack_page', ['hud_page', 'page', 'backpack_page', 'remove'], `
    <div class="top_bar">
      <div class="wrapper">
        <div class="left">
          <div class="money show_num_box">
            <img src="res/ui/icons/money.png" />
            <span>0</span>
          </div>
          <div class="stone show_num_box">
            <img src="res/ui/icons/stone.png" />
            <span>0</span>
          </div>
        </div>
        <div class="right">
          <p>负重：<span class="playerWeight"></span></p>
        </div>
      </div>
      <div class="select-btns">
        <div class="btns"></div>
      </div>
    </div>

    <div class="content">
      <div class="items">
      </div>
    </div>
    `);
  }
  
  initialize(){
    this.drawSelectBtn();

    this.drawItems();
  }

  drawSelectBtn(){
    let btnsWrapper = this.element.querySelector('.select-btns .btns');
    let items = Object.values(GoodTypeDefine);
    items.unshift({
      key: 'all',
      text: '全部',
      active: true
    })

    items.map(item => {
      let dom = makeDiv(btnsWrapper, '', [`btn`, `${item.key}`, item.active ? 'active' : ''], `
        ${item.text}
      `);

      this.trackClicks(dom, () => {
        btnsWrapper.querySelectorAll('.btn').forEach(item => {
          item.classList.remove('active')
        })
        dom.classList.add('active')

        this.drawItems(item.key);
      })
    })
  }

  drawItems(type = 'all'){
    this.drawBasicData();

    let items = this.root.backdrop.getExistsGoods().filter(item => {
      if(type == 'all') return true;
      return item.getType() == type;
    });
    let itemsParent = this.element.querySelector('.items')
    itemsParent.innerHTML = '';

    if(items.length > 0){
      items.map(item => {
        let num = item.attr.data.num || 1;
        let dom = makeDiv(itemsParent, '', ['item', 'styledButton', item.getLevel()], `
          ${item.getTitle()}
          <span class="num">${num == 1 ? '' : 'x' + num}</span>
        `)

        this.trackClicks(dom, () => {
          this.root.hud.parts.goodsBoard.handleShowGoodsBoard(item);
        });
      })
    } else {
      itemsParent.innerHTML = '<p>没有任何物品</p>'
    }
  }

  drawBasicData(){
    this.element.querySelector('.money span').innerHTML = this.root.mainPlayer.data.money;
    this.element.querySelector('.stone span').innerHTML = this.root.mainPlayer.data.stone;
    this.element.querySelector('.playerWeight').innerHTML = `
      ${keepDecimal(this.root.backdrop.getAllWeight(), 1)}/${this.root.mainPlayer.getWeightKg()}
    `;
  }
}